package com.supos.plugin.util;

import com.supos.plugin.bean.App;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Iterator;
import java.util.Set;

/**
 * date：2020/4/8 10:25
 * author  ：<xinwangji@supcon.com>
 */
public class ValidateUtil {


    public static <T> void validate(T obj) {
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        Validator validator = factory.getValidator();
        Set<ConstraintViolation<T>> constraintViolations = validator.validate(obj);
        Iterator<ConstraintViolation<T>> iter = constraintViolations.iterator();
        while (iter.hasNext()) {
            ConstraintViolation<T> error = iter.next();
            StringBuffer buffer = new StringBuffer().append("[")
                    .append(error.getPropertyPath().toString()).append("]")
                    .append(error.getMessage());
            throw new IllegalArgumentException(buffer.toString());
        }
    }

    public static void main(String[] args) {
        App app = new App();
        app.setAppVersion("11");
        ValidateUtil.validate(app);
    }
}
